package cn.chendd.shiro.custom;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author chendd
 * 自定义登录认证实现
 */
public class LoginRealm extends IniRealm {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public LoginRealm(String resourcePath) {
        super(resourcePath);
    }

    /**
     * 自定义认证器名称
     */
    @Override
    public String getName() {
        return "chendd-login-realem";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        logger.debug("待认证的用户名为：{}，密码为：{}" ,
                userToken.getUsername() , userToken.getPassword());
        SimpleAccount account = this.getUser(userToken.getUsername());
        if(account == null){
            throw new UnknownAccountException("用户不存在！");
        }
        if(! account.getCredentials().toString().equals(new String(userToken.getPassword()))){
            throw new AuthenticationException("用户名或密码不匹配！");
        }
        Object credentials = account.getCredentials();
        Object principal = token.getPrincipal();
        //将用户account对象存储至用户账号主体中
        SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(account , credentials , this.getName());
        return authInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取主体用户账号信息，将账号中的角色、权限信息进行授权
        SimpleAccount account = (SimpleAccount) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthor = new SimpleAuthorizationInfo();
        simpleAuthor.setRoles((Set<String>) account.getRoles());
        simpleAuthor.setObjectPermissions((Set<Permission>) account.getObjectPermissions());
        return simpleAuthor;
    }
}
